/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/Exceptions.hpp"
#include "Xern/Engine.hpp"
#include "SoundCache.hpp"

namespace XernAL
{
	SoundCache::SoundCache()
	{
	}

	SoundCache::~SoundCache()
	{
	}

	bool SoundCache::IsNoSound() const
	{
		return Engine::Get().GetSystemDescription().nosound;
	}

	boost::shared_ptr<SoundBuffer>
	SoundCache::CacheSound(boost::shared_ptr<ISoundSampler> sound)
	{
		// Find the sound in the cache.
		SoundMap::iterator it = soundMap.find(sound);
		if(it != soundMap.end())
		{
			boost::shared_ptr<SoundBuffer> buffer = it->second.lock();
			if(buffer)
				return buffer;
		}

		// Create a new sound buffer.
		boost::shared_ptr<SoundBuffer> ret(new SoundBuffer());
		ALuint buffer = ret->GetBuffer();

		// Read the format.
		ALenum format;
		int numchannels = sound->GetChannels();
		int sampleSize = sound->GetSampleSize();
		if(numchannels == 1)
		{
			if(sampleSize == 1)
				format = AL_FORMAT_MONO8;
			else if(sampleSize == 2)
				format = AL_FORMAT_MONO16;
			else
				throw XernException("Unsupported sample size.");
		}
		else if(numchannels == 2)
		{
			if(sampleSize == 1)
				format = AL_FORMAT_STEREO8;
			else if(sampleSize == 2)
				format = AL_FORMAT_STEREO16;
			else
				throw XernException("Unsupported sample size.");
		}
		else
			throw XernException("Only mono or stereo sound is supported.");

		// Read the sampler data.
		size_t dataSize = sound->GetChannels()*sound->GetSampleSize()*sound->GetSamples();
		char *data = new char[dataSize];
		sound->Read(dataSize, data);

		// Upload the buffer data.
		alBufferData(buffer, format, data, dataSize, sound->GetSampleRate());

		// Clean the temporal array.
		delete [] data;

		// Store the buffer.
		soundMap.insert(std::make_pair(sound, ret));

		// Return the buffer.
		return ret;
	}

}; // namespace XernAL
